package com.sale.system.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Author L
 * @Date 2021/12/21 10:58
 * @DESC excel工具类
 */
public class ExcelUtil<T> {

    /**
     * 实体对象
     */
    public Class<T> clazz;

    /**
     * 导入导出数据列表
     */
    private List<T> list;

    public void init(List<T> list) {
        this.list = list;
    }

    public ExcelUtil(Class<T> clazz)
    {
        this.clazz = clazz;
    }

    /**
     * 数据导出
     *
     * @param response 请求
     * @param data 数据
     * @param fileName sheet名称
     * @throws IOException 流异常
     */
    public void excelWriter(HttpServletResponse response, List<T> data, String fileName) throws IOException {
        //表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置表头居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, new WriteCellStyle());
        EasyExcel.write(response.getOutputStream(),clazz).sheet().sheetName(fileName).registerWriteHandler(horizontalCellStyleStrategy).doWrite(data);
    }

    /**
     * 模板导出
     *
     * @param response 请求
     * @param data 数据 null
     * @param fileName sheet名称
     * @throws IOException 流异常
     */
    public void exportTemplate(HttpServletResponse response, List<T> data, String fileName) throws IOException {
        //表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置表头居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, new WriteCellStyle());
        EasyExcel.write(response.getOutputStream(),clazz).sheet().sheetName(fileName).registerWriteHandler(horizontalCellStyleStrategy).doWrite(data);
    }

    /**
     * 导入
     *
     * @param is 流
     * @return
     */
    public List<T> importExcel(InputStream is) {
        // 解析每行结果在listener中处理
        ExcelListener listener = new ExcelListener();
        // 解析excel表格的数据，并且转换对应的实体对象类型
        EasyExcel.read(is,clazz,listener).sheet().doRead();
        // 获取表格里面的总数据量
        List<Object> datas = listener.getDatas();
        // 返回对应实体类型的数据
        return (List<T>) datas;
    }



}
